﻿using AutoMapper;
using Common;
using DB.Mapper.Attr;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace DB.Mapper
{
    public class MapsProfile : Profile
    {
        public MapsProfile()
        {
            IConfiguration configuration = Singleton<IConfiguration>.Instance;
            List<(Type Source, Type Target)> tuples = new List<(Type Source, Type Target)>();

            Type[] types = Assembly.Load(configuration["ModelAssembly"]).GetTypes();
            foreach (Type targetType in types)
            { 
                if (targetType.GetInterfaces().Contains(typeof(IOutputDto)))
                {
                    MapFromAttribute attribute = targetType.GetAttribute<MapFromAttribute>(true);
                    if (attribute != null)
                        foreach (Type sourceType in attribute.SourceTypes)
                        {
                            var tuple = ValueTuple.Create(sourceType, targetType);
                            tuples.AddIfNotExist(tuple);
                        }
                }
                else if (targetType.GetInterfaces().Contains(typeof(IInputDto)))
                {

                    MapToAttribute attribute = targetType.GetAttribute<MapToAttribute>(true);
                    if (attribute != null)
                        foreach (Type sourceType in attribute.TargetTypes)
                        {
                            var tuple = ValueTuple.Create(targetType,sourceType );
                            tuples.AddIfNotExist(tuple);
                        }

                }
            }


            foreach ((Type Source, Type Target) tuple in tuples)
            {
                CreateMap(tuple.Source, tuple.Target);
            }

        }
    }
}
